<template>
	<view>
		<!-- 导航栏 -->
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill"></image>
		<u-navbar title="节庆活动管理" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
			:titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder></u-navbar>

		<!-- 搜索与筛选 -->
		<view class="filter-wrap bgff">
			<!-- 关键词搜索 -->
			<view class="search-row">
				<u-search v-model="query.keyword" placeholder="请输入标题/上传人" showAction actionText="搜索" @search="onSearch"
					:actionStyle="{ color: '#0A993B' }" :height="30" :inputStyle="{ fontSize: '28rpx' }" />
			</view>

			<!-- 日期范围筛选 -->
			<view class="date-row">
				<text class="date-label">上传时间</text>
				<view class="date-inputs">
					<view class="date-input" @click="showStartDate = true">
						{{ query.startDate || '开始日期' }}
						<u-icon name="calendar" size="16" />
					</view>
					<text class="date-separator">至</text>
					<view class="date-input" @click="showEndDate = true">
						{{ query.endDate || '结束日期' }}
						<u-icon name="calendar" size="16" />
					</view>
				</view>
				<u-button text="重置" @click="resetFilter" size="small"
					:customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff', width: '120rpx', marginLeft: '16rpx' }" />
			</view>
		</view>

		<!-- 活动列表 -->
		<view class="policy-list">
			<view v-for="item in filteredList" :key="item.id" class="policy-item">
				<view class="policy-content">
					<view class="policy-title">{{ item.title }}</view>
					<view class="policy-info">举办地点: {{ item.location }}</view>
					<view class="policy-info">主办方: {{ item.organizer }}</view>
					<view class="policy-info">举办时间: {{ item.uploadTime }}</view>
					<view class="policy-summary">简介: {{ item.summary }}</view>
					<view class="policy-actions">
						<u-button size="small" text="查看" @click="onView(item)"
							:customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff' }" />
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-if="filteredList.length === 0 && !loading" class="empty">
				<u-empty mode="data" icon="data"></u-empty>
			</view>

			<!-- 加载状态 -->
			<view v-if="loading" class="loading">
				<u-loading-icon mode="spinner" size="28"></u-loading-icon>
				<text class="loading-text">{{ loadingMore ? '加载更多...' : '加载中...' }}</text>
			</view>

			<!-- 加载更多提示 -->
			<view v-if="!loading && hasMore && filteredList.length > 0" class="load-more">
				<text class="load-more-text">上拉加载更多</text>
			</view>

			<!-- 没有更多数据提示 -->
			<view v-if="!loading && !hasMore && filteredList.length > 0" class="no-more">
				<text class="no-more-text">没有更多数据了</text>
			</view>
		</view>

		<!-- 详情弹框 -->
		<u-popup :show="showDetail" mode="center" :round="18" :customStyle="{ width: '670rpx' }"
			@close="showDetail = false">
			<view class="detail-modal">
				<view class="detail-header">
					<text class="detail-title">政策法规详情</text>
					<u-icon name="close" size="28" color="#999" @click="showDetail = false"></u-icon>
				</view>
				<view class="detail-body">
					<view class="d-row">
						<text class="d-label">活动标题：</text>
						<text class="d-value">{{ currentItem.title }}</text>
					</view>
					<view class="d-row">
						<text class="d-label">主办方：</text>
						<text class="d-value">{{ currentItem.organizer }}</text>
					</view>
					<view class="d-row">
						<text class="d-label">上传人：</text>
						<text class="d-value">{{ currentItem.uploader }}</text>
					</view>
					<view class="d-row">
						<text class="d-label">上传时间：</text>
						<text class="d-value">{{ currentItem.uploadTime }}</text>
					</view>
					<view class="d-row">
						<text class="d-label">简介：</text>
						<text class="d-value">{{ currentItem.summary || '暂无正文内容' }}</text>
					</view>
					<view class="d-row">
						<text class="d-label">附件：</text>
						<text class="d-value attachment-text" @click="downloadAttachment(currentItem.attachmentUrl)"
							v-if="currentItem.attachmentUrl">{{ currentItem.attachments }}</text>
						<text class="d-value" v-else>暂无附件</text>
					</view>
				</view>
				<view class="detail-actions">
					<u-button @click="showDetail = false">关闭</u-button>
				</view>
			</view>
		</u-popup>

		<!-- 日期选择器 -->
		<u-datetime-picker :show="showStartDate" mode="date" :value="startDateValue" @confirm="startDateConfirm"
			@cancel="showStartDate = false" />
		<u-datetime-picker :show="showEndDate" mode="date" :value="endDateValue" @confirm="endDateConfirm"
			@cancel="showEndDate = false" />
	</view>
</template>

<script>
import navbarMixin from '@/common/navbarMixin'
import { getActivityList } from '@/api/economicforest'

export default {
	mixins: [navbarMixin],
	data() {
		return {
			query: {
				keyword: '',
				startDate: '',
				endDate: ''
			},
			showStartDate: false,
			showEndDate: false,
			showDetail: false,
			currentItem: {},
			list: [],
			loading: false,
			loadingMore: false,
			pageNum: 1,
			pageSize: 10,
			hasMore: true,
			startDateValue: new Date().getTime(),
			endDateValue: new Date().getTime()
		}
	},
	onLoad() {
		this.getActivityList()
	},
	onReachBottom() {
		// 触底加载更多
		if (this.hasMore && !this.loading) {
			this.loadMore()
		}
	},
	onPullDownRefresh() {
		// 下拉刷新
		this.refresh()
	},
	computed: {
		filteredList() {
			let result = this.list;

			// 关键词筛选
			if (this.query.keyword) {
				const keyword = this.query.keyword.toLowerCase();
				result = result.filter(item =>
					item.title.toLowerCase().includes(keyword) ||
					item.uploader.toLowerCase().includes(keyword)
				);
			}

			// 日期范围筛选
			if (this.query.startDate) {
				result = result.filter(item => item.uploadTime >= this.query.startDate);
			}

			if (this.query.endDate) {
				result = result.filter(item => item.uploadTime <= this.query.endDate);
			}

			return result;
		}
	},
	methods: {
		// 获取活动列表
		async getActivityList(isRefresh = false) {
			if (this.loading) return
			
			this.loading = true
			if (!isRefresh) {
				this.loadingMore = true
			}
			
			try {
				// 构建请求参数
				const params = {
					pageNum: isRefresh ? 1 : this.pageNum,
					pageSize: this.pageSize
				}
				
				// 添加搜索条件
				if (this.query.keyword && this.query.keyword.trim()) {
					params.query = this.query.keyword.trim()
				}
				
				// 添加时间范围
				if (this.query.startDate) {
					params.beginTime = this.query.startDate
				}
				if (this.query.endDate) {
					params.entTime = this.query.endDate
				}
				
				console.log('请求参数:', params)
				
				const response = await getActivityList(params)
				console.log('活动列表数据:', response)
				
				if (response && response.rows) {
					// 转换数据格式以匹配现有的显示结构
					const convertedData = response.rows.map(item => ({
						id: item.id,
						title: item.name || '未知活动',
						location: item.address || '未知地点',
						organizer: item.sponsor || '未知主办方',
						uploader: item.createBy || '未知上传人',
						uploadTime: item.startTime || item.createTime || '未知时间',
						summary: item.content || '暂无简介',
						content: item.content || '暂无详情',
						attachments: item.file ? '活动附件.pdf' : '暂无附件',
						attachmentUrl: item.file || null,
						// 保留原始数据
						originalData: item
					}))
					
					if (isRefresh) {
						this.list = convertedData
						this.pageNum = 1
					} else {
						this.list = [...this.list, ...convertedData]
					}
					
					// 判断是否还有更多数据
					this.hasMore = response.rows.length === this.pageSize
					if (this.hasMore) {
						this.pageNum++
					}
				}
			} catch (error) {
				console.error('获取活动列表失败:', error)
				uni.showToast({
					title: '获取数据失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
				this.loadingMore = false
			}
		},
		
		// 加载更多
		async loadMore() {
			if (this.hasMore && !this.loading) {
				await this.getActivityList(false)
			}
		},
		
		// 刷新数据
		async refresh() {
			this.pageNum = 1
			this.hasMore = true
			await this.getActivityList(true)
			// 停止下拉刷新
			uni.stopPullDownRefresh()
		},
		async onSearch() {
			// 搜索功能
			this.pageNum = 1
			this.hasMore = true
			await this.getActivityList(true)
		},
		async resetFilter() {
			this.query.keyword = '';
			this.query.startDate = '';
			this.query.endDate = '';
			// 重置日期选择器的值为今天
			this.startDateValue = new Date().getTime();
			this.endDateValue = new Date().getTime();
			this.pageNum = 1
			this.hasMore = true
			await this.getActivityList(true)
		},
		async startDateConfirm(e) {
			const date = new Date(e.value);
			this.query.startDate = this.formatDate(date);
			this.startDateValue = e.value; // 更新选择器的值
			this.showStartDate = false;
			this.pageNum = 1
			this.hasMore = true
			await this.getActivityList(true)
		},
		async endDateConfirm(e) {
			const date = new Date(e.value);
			this.query.endDate = this.formatDate(date);
			this.endDateValue = e.value; // 更新选择器的值
			this.showEndDate = false;
			this.pageNum = 1
			this.hasMore = true
			await this.getActivityList(true)
		},
		onView(item) {
			this.currentItem = item;
			this.showDetail = true;
		},
		formatDate(date) {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		},
		downloadAttachment(attachmentUrl) {
			if (!attachmentUrl) {
				uni.showToast({ title: '附件不存在', icon: 'none' });
				return;
			}

			uni.showLoading({ title: '下载中...' });

			// 使用uni.downloadFile下载真实文件
			uni.downloadFile({
				url: attachmentUrl,
				success: (res) => {
					uni.hideLoading();
					if (res.statusCode === 200) {
						uni.showToast({
							title: '下载成功',
							icon: 'success',
							duration: 2000
						});

						// 保存文件到本地
						uni.saveFile({
							tempFilePath: res.tempFilePath,
							success: (saveRes) => {
								uni.showModal({
									title: '文件下载完成',
									content: `文件已保存到本地，是否打开预览？`,
									success: (modalRes) => {
										if (modalRes.confirm) {
											// 尝试打开文件
											uni.openDocument({
												filePath: saveRes.savedFilePath,
												success: (openRes) => {
													uni.showToast({
														title: '文件打开成功',
														icon: 'success'
													});
												},
												fail: (err) => {
													uni.showToast({
														title: '文件打开失败',
														icon: 'none'
													});
												}
											});
										}
									}
								});
							},
							fail: (err) => {
								uni.showToast({
									title: '文件保存失败',
									icon: 'none'
								});
							}
						});
					} else {
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					uni.hideLoading();
					uni.showToast({
						title: '下载失败',
						icon: 'none'
					});
					console.error('下载失败:', err);
				}
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.mine-navbar-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 750rpx;
	
	z-index: 1;
}

.filter-wrap {
	padding: 20rpx;
	background: #fff;
}

.search-row {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
}

.date-row {
	display: flex;
	align-items: center;
}

.date-label {
	color: #333;
	width: 120rpx;
	font-size: 28rpx;
}

.date-inputs {
	flex: 1;
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.date-input {
	flex: 1;
	height: 72rpx;
	padding: 0 13rpx;
	background: #f5f5f5;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	color: #666;
}

.date-separator {
	color: #666;
	font-size: 28rpx;
}

.policy-list {
	padding: 20rpx;
}

.policy-item {
	display: flex;
	flex-direction: column;
	padding: 20rpx;
	background: #fff;
	border-radius: 16rpx;
	margin-bottom: 16rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.policy-content {
	flex: 1;
}

.policy-title {
	font-size: 30rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 20rpx;
}

.policy-info {
	font-size: 26rpx;
	color: #666;
	margin-bottom: 20rpx;
}

.policy-summary {
	font-size: 26rpx;
	color: #999;
	line-height: 1.4;
	margin-bottom: 16rpx;
}

.policy-actions {
	display: flex;
	justify-content: flex-end;
}

/* 详情弹框 */
.detail-modal {
	background: #fff;
	border-radius: 18rpx;
	overflow: hidden;
}

.detail-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 28rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.detail-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.detail-body {
	padding: 24rpx 28rpx;
}

.d-row {
	display: flex;
	margin-bottom: 14rpx;
	align-items: baseline;
}

.d-label {
	width: 200rpx;
	color: #666;
	font-size: 26rpx;
}

.d-value {
	flex: 1;
	color: #333;
	font-size: 26rpx;
}

.attachment-text {
	color: #007bff;
	/* 蓝色 */
	text-decoration: underline;
	cursor: pointer;
}

.detail-actions {
	padding: 20rpx 28rpx 28rpx;
	display: flex;
	justify-content: center;
}

.empty {
	padding: 80rpx 0;
	text-align: center;
}

.loading {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 40rpx 0;
}

.loading-text {
	margin-left: 10rpx;
	color: #999;
	font-size: 26rpx;
}

.load-more {
	padding: 30rpx 0;
	text-align: center;
}

.load-more-text {
	color: #999;
	font-size: 26rpx;
}

.no-more {
	padding: 30rpx 0;
	text-align: center;
}

.no-more-text {
	color: #ccc;
	font-size: 24rpx;
}
</style>
